//
//  SLStatusListViewModel.swift
//  Sina15
//
//  Created by 盼 on 16/4/12.
//  Copyright © 2016年 pan. All rights reserved.
//

import UIKit

class SLStatusListViewModel: NSObject {
    
    //定义一个模型数组
    var statusModels:[SLStatusViewModel] = [SLStatusViewModel]()
    
    }

extension SLStatusListViewModel {
    
    func loadHomePage(isPullup: Bool,finished:(isSuccess: Bool)->()){
        
        var max_id : Int64 = 0
        var since_id: Int64 = 0
        if isPullup {
            //上拉加载显示更多
            max_id = statusModels.last?.status?.id ?? 0
        }else{
            //下拉加载刷新
         since_id = statusModels.first?.status?.id ?? 0
        }
        
        print(max_id)
        //获取用户的access_token
        guard let token = SLUserViewModel.sharedModel.userAccount?.access_token else {
    
        print("数据加载错误")
            
//            finished(isSuccess: false)
    
        return
        }
        
        AFNetWorkTool.sharedTools.loadHomePage(token,max_id: max_id,since_id: since_id) { (response, error) -> () in
            
            if error != nil {
                
                print("加载微博错误")
                finished(isSuccess: false)
                return
            }
            
//            print(response)
            
            //把返回的数据转换成字典
            guard let dict = response as? [String: AnyObject] else {
                
//                SVProgressHUD.showErrorWithStatus("数据格式错误")
                finished(isSuccess: false)
                return
            }
            
            //把微博数据status转换成数组模型
            guard let array = dict["statuses"] as? [[String: AnyObject]] else {
                
//                SVProgressHUD.showErrorWithStatus("数据格式错误")
                finished(isSuccess: false)
                return
            }
            
            //把微博数据转换成模型对象
            var tempArray: [SLStatusViewModel] = [SLStatusViewModel]()
            
            for statusDict in array {
                
                //字典转模型
                let status:SLStatus = SLStatus(dict: statusDict)
                
                //创建statusModel对象
                let statusModel = SLStatusViewModel(status: status)
                
                tempArray.append(statusModel)
            }
            
            //把模型对象保存到模型数组中
            if isPullup {
                self.statusModels = self.statusModels + tempArray
            }else {
                self.statusModels = tempArray + self.statusModels
            }
            
//            self.statusModels = tempArray
            //加载数据成功
            finished(isSuccess: true)
        }

    }
}


